/**
 * Copyright (C) 2006 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.gotom.core.example;

import static com.opensymphony.xwork2.Action.SUCCESS;


import java.util.HashSet;
import java.util.Set;


import cn.gotom.core.pojos.Role;
import cn.gotom.core.pojos.User;
import cn.gotom.core.service.RoleService;
import cn.gotom.core.service.UserService;
import cn.gotom.core.web.Counter;

import com.google.inject.Inject;
import com.opensymphony.xwork2.ActionContext;

public class Count
{

	final Counter counter;
	final Service service;
	String message = "";

	@Inject
	private RoleService roleService;

	@Inject
	private UserService userService;

	@Inject
	public Count(Counter counter, Service service)
	{
		this.counter = counter;
		this.service = service;
	}

	public String execute()
	{
		return SUCCESS;
	}

	public int getCount()
	{
		return counter.increment();
	}

	public String getStatus()
	{
		return service.getStatus();
	}

	public String getMessage()
	{
		try
		{
			ActionContext.getContext().get(ActionContext.ACTION_NAME);
			Role role = roleService.get("name", "peixere");
			if (role == null)
			{
				role = new Role();
				role.setName("peixere");
			}
			roleService.save(role);

			User user = userService.get("username", "peixere");
			if (user == null)
			{
				user = new User();
				user.setUsername("peixere");
				user.setPassword("admin");
				user.setName("name");
				Set<Role> roles = new HashSet<Role>();
				user.setRoles(roles);
			}
			if (!user.getRoles().contains(role))
			{
				user.getRoles().add(role);
			}
			userService.save(user);

			System.out.println(userService.findAll().size() > 0);

		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{

		}
		return message + userService.findAll().size();
	}

	public void setMessage(String message)
	{
		this.message = message;
	}
}
